#!/usr/bin/env python
# encoding=utf-8

import os
import sys
from json import loads

import requests

from xawesome_util import sha256

reload(sys)
sys.setdefaultencoding('utf-8')

__author__ = 'xlzd'

BASE_URL = 'http://{host}:{port}/api/upload'
CHECK_URL = 'http://{host}:{port}/api/check'


class Qiniu(object):
    def __init__(self, bucket, host, port=7300):
        self._bucket = bucket
        self._post_url = BASE_URL.format(host=host, port=port)
        self._check_url = CHECK_URL.format(host=host, port=port)

    def upload(self, filedata, suffix='', mime_type='application/octet-stream'):
        filename = sha256(filedata)
        if suffix:
            filename = filename + '.' + (suffix, suffix[1:])[suffix.startswith('.')]
        check = requests.get(self._check_url, {'filename': filename, 'bucket': self._bucket})
        if 2 != check.status_code / 100:
            check = requests.post(
                self._post_url,
                files={'file': (filename, filedata, mime_type)},
                data={'bucket': self._bucket}
            )
        # print 'check', check.content
        return loads(check.content)

    def upload_file(self, filepath, suffix='', mime_type='application/octet-stream'):
        with open(filepath, 'rb') as fp:
            filedata = fp.read()
        if not suffix:
            basename = os.path.basename(filepath).split('.')
            suffix = '' if len(basename) < 2 else basename[-1]
        return self.upload(filedata, suffix=suffix, mime_type=mime_type)


# ---------------- useage -------------------


def main():
    q = Qiniu(bucket='bucket name', host='server address')

    q.upload_file('file path')
    q.upload('data')


if __name__ == '__main__':
    main()
